import pyautogui
import json
import random
import time

FIND_DEVICES_PATH = "find_devices.png"
GET_INFO_PATH = "get_info.png"
PROGRAM_PATH = "program.png"
CYCLE_PATH = "cycle.png"
YES_PATH = "yes.png"

# 假设软件界面已经打开
def batch_change(batch_number=1, fpga="minisys", image_path="./image_path/", 
                 config_path="./usb_refresh_config.json", serial_number_path="./serial_number.json",
                 test=False):
    """
    根据config_path中的配置批量烧写usb信息，通过image_path中的图片进行定位控制
    """
    serial_number_set = set()

    try:
        # 读取usb配置信息
        with open(config_path, "r") as fp:
            usb_refresh_cfg = json.load(fp)
            fpga_cfg = usb_refresh_cfg[fpga]

        # 加载序列号信息
        if not test:
            with open(serial_number_path, "r") as fp:
                serial_number_set = set(json.load(fp))
                print(serial_number_set)

        # 每轮烧写一个fpga板的usb信息
        for _ in range(batch_number):

            # Step 1: Find Devices
            location_find_devices = pyautogui.center(pyautogui.locateOnScreen(image_path + FIND_DEVICES_PATH))
            pyautogui.click(location_find_devices, duration=0.5)

            # Step 2: Get Info
            # 看起来这一步好像没有必要，因为本函数将手动修改其中的大部分信息
            location_get_info = pyautogui.center(pyautogui.locateOnScreen(image_path + GET_INFO_PATH))
            pyautogui.click(location_get_info, duration=0.5)

            # Step 3: Select the information preset for the device!
            special_item = ("enable_vcp_driver_A", "enable_vcp_driver_B", "self_powered", "power")
            for info_item in fpga_cfg:
                location_item = pyautogui.locateOnScreen(image_path + info_item + ".png")
                location_item = location_item.left, location_item.top + location_item.height // 2 
                if info_item not in special_item:
                    pyautogui.click(location_item + (250, 0), duration=0.1)
                    pyautogui.hotkey("ctrl", "a")
                    pyautogui.press("delete")
                    if info_item == "serial_number":
                        while True:
                            ten_digit_string = "".join(random.choices("0123456789", k=10))
                            serial_number_string = fpga_cfg[info_item] + ten_digit_string
                            if serial_number_string not in serial_number_set:
                                serial_number_set.add(serial_number_string)
                                break
                        pyautogui.write(serial_number_string)
                    else:
                        pyautogui.write(fpga_cfg[info_item])

                else :
                    if info_item != "power":
                        # 如果板子的usb信息默认就是这样的话，我想我们就没必要去更改了
                        # todo: 找到复选框位置
                        # todo: 判断复选框状态
                        # todo: 将复选框设置为指定状态
                        ...
                    else:
                        pyautogui.click(location_item + (150, 0), duration=0.1)
                        pyautogui.hotkey("ctrl", "a")
                        pyautogui.press("delete")
                        pyautogui.write(fpga_cfg[info_item])

            # Step 4: Program
            if not test:
                location_program = pyautogui.center(pyautogui.locateOnScreen(image_path + PROGRAM_PATH))
                pyautogui.click(location_program, duration=0.1)
                time.sleep(0.5)
                location_yes = pyautogui.center(pyautogui.locateOnScreen(image_path + YES_PATH))
                pyautogui.click(location_yes)

            # Step 5: Cycle
            location_cycle = pyautogui.center(pyautogui.locateOnScreen(image_path + CYCLE_PATH))
            pyautogui.click(location_cycle)

        # 写回序列号信息
        if not test:
            with open(serial_number_path, "w") as fp:
                json.dump(list(serial_number_set), fp)
            
    except KeyError as e:
        print(f"KeyError: Your fpga type {e} is not support.")
    except IOError as e:
        print("IOError:", e)
    except pyautogui.ImageNotFoundException as e:
        print("ImageNotFoundException:", e)


if __name__ == "__main__":
    
    batch_change(1, "minisys", test=True)